#!/bin/bash

# 保存备份的个数
number=5

del_file() {
    if [ $1 -gt $number ]; then
        rm $2 -rf && echo "delete $2 successfully" >> $3
    fi
}

restore() {
    if [ -e $1 ];then
        rm $1
        touch "$1"
    else
        touch "$1"
    fi
}

getProc() {
    st=$(grep -in "^delimiter\ [|$]" $1 | awk -F':' '{ print $1 }')
    end=$(grep -in "^delimiter\ ;" $1 | awk -F':' '{ print $1 }')
    sed -n "${st},${end}p" $1 >> $2
}

getAPIMes() {
    filename=$(basename $1 .sql)
    echo -e "{\n\t--  $filename" >> $2
    params=$(grep "^--" $1)
    while read line; do
        echo -e "\t$line" >> $2
    done <<< "$params"
    echo -e "}\n" >> $2
}

getdir(){
    for element in $(ls $1)
    do
        dir_or_file=$1"/"$element
        if [ -d $dir_or_file ]
        then
            getdir $dir_or_file $2 $3
        else
            ftype=${dir_or_file##*.}
            if [ "sql" = $ftype ]; then
                echo "$dir_or_file"
                view=$(echo "$dir_or_file" | grep "view")
                if [ ! -n "$view" ];then
                    getProc "$dir_or_file" $2
                    getAPIMes "$dir_or_file" $3
                else
                    view_len=$(wc -l $view | awk '{ print $1 }')
                    sed -n "2,${view_len}p" $view >> $2
                fi
            fi
        fi
    done
}

usage () {
    echo "Usage-1: ./sync.sh -d barda -p /tmp/procedure -s /tmp"
    echo "Usage-2: ./sync.sh --db barda --pdir /tmp/procedure/ --sdir /tmp"
}
source ~/.bashrc
dt=$(date +%F_%H-%M)
db="barda"
ip=$IP
port=3306
proc_dir="$HOME/workspaces/bar-database/procedure/barda"
save_dir="$HOME/db_storage/backup"

while [ "$#" -ge 2 ]
do
    case "$1" in
        -d|--db) shift 1; db=$1; shift 1 ;;
        -p|--pdir) shift 1; proc_dir=$1; shift 1 ;;
        -s|--sdir) shift 1; save_dir=$1; shift 1 ;;
    esac
done

api_file="$HOME/workspaces/bar-database/procedure/${db}_api.txt"
log_file="$HOME/workspaces/bar-database/procedure/.${db}_proc.log"
source_file="${save_dir}/${db}_pfv_${dt}.sql"
backup_file="$HOME/db_storage/backup/sync/bak_${db}_pfv.sql"


# 帮助命令
case "$1" in
    -h|help) usage; exit 0;;
esac

echo "$dt begin=======================================" >> $log_file
restore $source_file
restore $api_file
getdir "$proc_dir" "$source_file" "$api_file" | tee $log_file

sed -i "1iuse $db -A;" $source_file
mysql -h $ip -P $port -uroot -p1234 -e "source ${source_file};"
cp $source_file $backup_file

# 删除多余的备份
barda_pfv=`ls -l -crt "$save_dir" | awk '{ print $9 }' | grep "${db}_pfv_$(date +%Y)"`
pfv_count=$(ls ${save_dir} | grep "${db}_pfv_" | wc -l)
del_file $pfv_count `echo "${save_dir}/${barda_pfv}" | head -n 1` $log_file
echo "$dt end=======================================" >> $log_file
